package com.mugui.spring.net.websocket;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.mugui.spring.net.bean.NetBag;
import com.mugui.spring.net.websocket.WebSocketTask.ThreadTask;


@ServerEndpoint("/")
@Component
public class WebHandle {

	private WebSocketSessionManager webSocketSessionManager;
	{
		ApplicationContext app = (ApplicationContext) System.getProperties().get("Application");
		if (app != null) {
			webSocketSessionManager = app.getBean(WebSocketSessionManager.class);
			webSocketTask = app.getBean(WebSocketTask.class);
		}
	}

	@OnOpen
	public void onOpen(Session session) {
		webSocketSessionManager.add(session.getId(), session);
	}

	@OnMessage
	public void onMessage(Session session, byte[] message) {
		NetBag bag = NetBag.newBean(NetBag.class, new String(message));
		if (bag.getFunc().startsWith("sub.")) {
			bag.setFunc(bag.getFunc().substring(4));
			webSocketSessionManager.sub(session, bag);
		} else if (bag.getFunc().startsWith("unsub.")) {
			bag.setFunc(bag.getFunc().substring(6));
			webSocketSessionManager.unsub(session, bag);
		}
	}

	@OnMessage
	public void onMessage(Session session, String message) {
		NetBag bag = NetBag.newBean(NetBag.class, message);
		if (bag.getFunc().startsWith("sub.")) {
			bag.setFunc(bag.getFunc().substring(4));
			webSocketSessionManager.sub(session, bag);
		} else if (bag.getFunc().startsWith("unsub.")) {
			bag.setFunc(bag.getFunc().substring(6));
			webSocketSessionManager.unsub(session, bag);
		}
	}

	private WebSocketTask webSocketTask;

	@OnError
	public void onError(Session session, Throwable error) throws Throwable {
		webSocketSessionManager.del(session.getId());
		error.printStackTrace();
		ThreadTask remove = webSocketTask.getTHREAD_MAP().remove(session.getId());
		if (remove != null) {
			remove.time = 0;
		}
	}

	@OnClose
	public void onClose(Session session) {
		webSocketSessionManager.del(session.getId());
		ThreadTask remove = webSocketTask.getTHREAD_MAP().remove(session.getId());
		if (remove != null) {
			remove.time = 0;
		}
	}

}
